package com.company;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;


public class Main {

    public static void main(String[] args) throws IOException {
	    System.out.println("start");
        // This function Calls LOGIN API to get token for future use
        String str = getToken("http://202.120.47.213:12345","usr","psw");
        System.out.println("Get Token : " + str);
    }

    static String genJson(String name, String psw){
        JSONObject matadata = new JSONObject();
        matadata.put("TimeStamp",123124233);
        matadata.put("Device", "android");
        JSONObject userinfo = new JSONObject();
        userinfo.put("username", name);
        userinfo.put("password", psw);

        JSONObject data = new JSONObject();
        data.put("mataData",matadata);
        data.put("userinfo", userinfo);
        return data.toJSONString();
    }

    static java.lang.String getToken(String surl, String name, String psw) throws IOException {
        String jsonstr = genJson(name, psw);
        URL url  = new URL(surl + "/login");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type","application/json");
        conn.setRequestProperty("Content-Length",String.valueOf(jsonstr.length()));
        conn.getOutputStream().write(jsonstr.getBytes());

        String ostr = IOUtils.toString(conn.getInputStream());
        System.out.println(ostr);

        org.json.JSONObject outjson = new org.json.JSONObject(ostr);
        return outjson.getString("token");
    }
}


